using System.Text;
using Gateway.Common.Models;
using Gateway.IQuery;
using Gateway.IQuery.UploadFiles;
using Gateway.IQuery.UploadFiles.Request;
using Gateway.IQuery.UploadFiles.Result;
using Gateway.IRepositories;
using Microsoft.Extensions.Options;
using SqlSugar;

namespace Gateway.Query;

///  <summary>
/// 上传文件查询服务
/// </summary>
public class UploadFilesQuery : IUploadFilesQuery
{
    private readonly IOptionsMonitor<UploadOption> _option;
    private readonly IQueryRepository _queryRepository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="repository"></param>
    /// <param name="option"></param>
    public UploadFilesQuery(IQueryRepository repository, IOptionsMonitor<UploadOption> option)
    {
        _queryRepository = repository;
        _option = option;
    }

    /// <summary>
    /// 获取分页列表
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<PageResult<UploadFilesDetailResult>> GetPageList(FilesPageListRequest request)
    {
        StringBuilder builder = new StringBuilder(500);
        builder.Append(@"where Deleted='N' and Disabled='N'");

        if (!string.IsNullOrEmpty(request.FileName))
        {
            builder.Append(" and uf.OriginName =@FileName ");
        }

        if (!string.IsNullOrEmpty(request.FileNo))
        {
            builder.Append(" and uf.FileNo =@FileNo ");
        }

        if (!string.IsNullOrEmpty(request.FileUrl))
        {
            builder.Append(" and uf.Path =@FileUrl ");
        }

        if (!string.IsNullOrEmpty(request.StartTime))
        {
            builder.Append(" and uf.CreatedTime >=@StartTime ");
        }

        if (!string.IsNullOrEmpty(request.EndTime))
        {
            builder.Append(" and uf.CreatedTime <=@EndTime ");
        }

        string countSql = $@"select count(1) from  UploadFiles uf {builder}";
        string listSql = $@"select * from  UploadFiles uf {builder} order by uf.CreatedTime desc  limit {(request.Page-1)*request.PageSize},{request.PageSize}";
        var list = (await _queryRepository.QueryAsync<UploadFilesDetailResult>(listSql, request)).ToList();
        var count = await _queryRepository.QueryFirstOrDefaultAsync<int>(countSql, request);
        foreach (var item in list)
        {
            string fullPath = _option.CurrentValue.Domain+"/" +  item.Path;
            item.Url= fullPath;
        }
        return PageResult<UploadFilesDetailResult>.Create(list, count);
    }
}